package com.ypj.indusynergyems.common.biz.user;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;

import com.ypj.indusynergyems.common.convention.exception.ClientException;
import com.ypj.indusynergyems.common.convention.result.Results;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

import static com.ypj.indusynergyems.common.enums.UserErrorCodeEnum.USER_TOKEN_FAIL;


/**
 * 用户信息传输过滤器
 */
@RequiredArgsConstructor
public class UserTransmitFilter implements Filter {
    private final StringRedisTemplate stringRedisTemplate;

    // 静态资源目录前缀列表（这里假设它们是标准的，但您可以根据需要调整）
    private static final List<String> STATIC_RESOURCES_PREFIXES = Arrays.asList(
            "/static/", "/css/", "/js/", "/images/"
    );

    private static final List<String> IGNORE_URI = Lists.newArrayList(
            "/system/login",
            "/system/has-username",
            "/login.html"
    );

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String requestURI = httpServletRequest.getRequestURI();
        // 检查请求URI是否以静态资源目录前缀开头
        boolean isStaticResource = STATIC_RESOURCES_PREFIXES.stream()
                .anyMatch(prefix -> requestURI.startsWith(prefix));

        // 如果请求是静态资源或已明确忽略，则直接调用filterChain
        if (isStaticResource || IGNORE_URI.contains(requestURI)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String method = httpServletRequest.getMethod();
        if (!(Objects.equals(requestURI, "/login.html"))) {
            String phone = httpServletRequest.getHeader("phone");
            String token = httpServletRequest.getHeader("token");
            if (!StrUtil.isAllNotBlank(phone, token)) {
                returnJson((HttpServletResponse) servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
                return;
            }
            Object userInfoJsonStr = null;
            try {
                userInfoJsonStr = stringRedisTemplate.opsForHash().get("login_" + phone, token);
                if (userInfoJsonStr == null) {
                    throw new ClientException(USER_TOKEN_FAIL);
                }
            } catch (Exception e) {
                returnJson((HttpServletResponse) servletResponse, JSON.toJSONString(Results.failure(new ClientException(USER_TOKEN_FAIL))));
                return;
            }
            UserInfoDTO userInfoDTO = JSON.parseObject(userInfoJsonStr.toString(), UserInfoDTO.class);
            UserContext.setUser(userInfoDTO);
        }

        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserContext.removeUser();
        }
    }

    /*返回客户端数据*/
    private void returnJson(HttpServletResponse response, String json) throws Exception {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {

        } finally {
            if (writer != null) {
                writer.close();
            }
        }

    }
}